package com.maoxx.humanresourcemanage_service.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.maoxx.humanresourcemanage_service.entity.Staff;
import com.maoxx.humanresourcemanage_service.enums.BusinessStatusEnum;
import com.maoxx.humanresourcemanage_service.exception.ServiceException;
import com.maoxx.humanresourcemanage_service.service.StaffService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @className: JWTInterceptor
 * @author: Maoxx
 * @date: 2024/11/6 19:13
 * @Version: 1.0
 * @description:
 */

public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private StaffService staffService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        // 检查token是否为空
        if (StrUtil.isNotBlank(token)) {
            // 获取token中的用户id
            Integer id = Integer.valueOf(JWT.decode(token).getAudience().get(0));
            Staff staff = staffService.getById(id);

            if (staff != null) {
                // 判断员工状态是否正常
                if (staff.getStatus() == 1) {
                    // 创建JWTVerifier对象，验证token
                    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(staff.getPassword())).build();
                    try {
                        verifier.verify(token); // 验证token的有效性
                    } catch (JWTVerificationException e) {
                        throw new ServiceException(BusinessStatusEnum.TOKEN_INVALID); // token无效异常
                    }
                    return true;
                }
                throw new ServiceException(BusinessStatusEnum.STAFF_STATUS_ERROR); // 员工状态异常
            }
            throw new ServiceException(BusinessStatusEnum.NOT_EXIST); // 用户不存在
        }
        throw new ServiceException(BusinessStatusEnum.TOKEN_NOT_EXIST); // token不存在
    }
}
